package com.cloud_notes.demo.controller;


import com.cloud_notes.demo.common.pojo.response.BlogDetailsInfoResponse;
import com.cloud_notes.demo.common.pojo.response.BlogInfoResponse;
import com.cloud_notes.demo.service.BlogService;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


@Slf4j
@RequestMapping("/blog")
@RestController
public class BlogController {
    @Resource(name = "blogServiceImpl")
    private BlogService blogService;

    //图片安全存储接口
    @RequestMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        // 校验文件类型
        String contentType = file.getContentType();
        if (!Arrays.asList("image/jpeg", "image/png").contains(contentType)) {
            //throw new InvalidFileTypeException();
        }
        // 生成安全文件名
        String safeFileName = UUID.randomUUID() + "_" + System.currentTimeMillis();
        Path targetPath = Paths.get("public/uploads/" + safeFileName);

        // 保存文件
        Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

        return "/uploads/" + safeFileName;
    }

    //获取云笔记数据库数据
    @RequestMapping("/getList")
    public List<BlogInfoResponse> getList(){
        log.info("获取笔记列表信息……");
        List<BlogInfoResponse> blogInfoResponses = blogService.getList();
        // 遍历处理每个博客对象
        blogInfoResponses.forEach(blog -> {
            String originalContent = blog.getContent(); // 假设原始内容字段为content
            blog.setTruncatedContent(originalContent);
        });
        return blogInfoResponses;
    }


    //获取云笔记的详情信息
    @RequestMapping("/getBlogDetails")
    public BlogDetailsInfoResponse getBlogDetails(@NotNull Integer blogId){
        log.info("获取云笔记的详情信息：blogId:{}",blogId);
        //参数检验：可以用if……else进行校验，还可以用注解方式（先添加依赖jakarta.validation）
        return blogService.getBlogDetails(blogId);
    }

}
